<?php

namespace cf\api\shop;

require_once dirname(__FILE__).'/../shop.php';
require_once dirname(__FILE__).'/../db.php';
require_once dirname(__FILE__).'/admin.php';

function getCategories($parentId=null, &$items=array(), $showDisabled=true)
{
	$groups = new \cf\ChildGroups($parentId,$showDisabled);
	foreach ($groups as $g) {
		$item = array( '' => array('id' => $g->id(), 'code' => $g->code()) );
		getCategories($g->id(), $item, $showDisabled);
		$items[$g->name()] = $item;
	}
	return $items;
}

/**
	@param $parentId  category ID or CODE or PATH OF CODES (e.g. /cars/bmw/x-5)
*/
function getCategoriesTree($parentId=null, $showHidden=false, $maxDepth=0, $path='', $depth=1)
{
	if ($maxDepth && $depth > $maxDepth) {
		return array();
	}
	static $q = null;
	\cf\createStaticQuery($q,"
		SELECT id, parent_id, name, hidden, IFNULL(code,id) AS code, image, page_title, page_keywords, page_descr, short_descr
		FROM cf_groups
		WHERE (parent_id=:parentId OR (:parentId IS NULL AND parent_id IS NULL))
			". ($showHidden ? '' : 'AND (hidden IS NULL OR hidden=0)') . "
		ORDER BY sort_order ASC
	");
	$items = \cf\query2arrays($q, array('parentId' => \cf\Group::toID($parentId)), false, 'code');
	
	foreach ($items as $id => $item) {
		$items[$id]['depth'] = $depth;
		$items[$id]['path'] = $path.'/'.$items[$id]['code'];
		$items[$id]['children'] = getCategoriesTree($id, $showHidden, $maxDepth, $items[$id]['path'], ++$depth);
	}
	
	return $items;
}

function findCategories($search, $path='', $showHidden=false)
{
	$params = array();
	$sqlSearch = array();
	if ($search) {
		$search = is_array($search) ? $search : array($search);
		for ($i=0; $i<count($search); ++$i) {
			$sqlSearch[] = "(
				name LIKE CONCAT('%',:search{$i},'%') OR
				short_descr LIKE CONCAT('%',:search{$i},'%') OR
				descr LIKE CONCAT('%',:search{$i},'%')
			)";
			$params["search{$i}"] = $search[$i];
		}
	}
	$IDs = \cf\query2vector("
		SELECT id
		FROM cf_groups
		WHERE ".implode(' AND ',$sqlSearch).($showHidden ? '' : ' AND (hidden IS NULL OR hidden=0)'),
		$params
	);

	$categories = array();
	foreach ($IDs as $id) {
		$categories[] = getCategory($id, $path);
	}
	
	return $categories;
}


/**
	@param $id  category ID or CODE or PATH OF CODES (e.g. /cars/bmw/x-5)
*/
function getCategory($id, $path='')
{
	$cat = \cf\Group::get($id);
	
	$branch = array();
	$branchCats = new \cf\BranchGroups($cat->id());
	foreach ($branchCats as $bCat) {
		$path .= '/'.$bCat->code();
		$branch[] = array(
			'id' => $bCat->id(),
			'code' => $bCat->code(),
			'name' => $bCat->name(),
			'path' => $path
		);
	}

	return array(
		'id' => $cat->id(),
		'code' => $cat->code(),
		'parent_id' => $cat->parentId(),
		'name' => $cat->name(),
		'hidden' => $cat->hidden(),
		'image' => $cat->image(),
		'short_descr' => $cat->shortDescr(),
		'descr' => $cat->descr(),
		'page_title' => $cat->pageTitle(),
		'page_keywords' => $cat->pageKeywords(),
		'page_descr' => $cat->pageDescr(),
		'branch' => $branch,
		'path' => $path,
		'children_count' => $cat->childrenCount()
	);
}

function getCategoryAttributes($catId, $skipNull=false)
{
	$attributes = array();
	$attrs = new \cf\GroupAttributes($catId, $skipNull);
	foreach ($attrs as $a) {
		$attributes[] = array(
			'id' => $a->id(),
			'code' => $a->code(),
			'name' => $a->name(),
			'value' => $a->value(),
			'isNull' => $a->isNull(),
			'type' => $a->type(),
			'length' => $a->length(),
			'scale' => $a->scale(),
			'isList' => $a->isList(),
			'allowedValues' => $a->allowedValues()
		);
	}
	return $attributes;
}
/*
function countProducts($groupIDs, $mustBeInIDs=array(), $manufacturerIDs=array())
{
	countAll()
}*/

function getProducts($groupIDs, $mustBeInIDs=array(), $manufacturerIDs=array(), $attributes=array(), $skip=null, $limit=null)
{
	$products = new \cf\Products($groupIDs);
	$products->mustBeIn($mustBeInIDs);
	$products->filterByManufacturers($manufacturerIDs);
	$products->filterByAttributes($attributes);
	$prodList = $products->getList($skip, $limit);
	
	$l = array();
	foreach ($prodList as $product) {
		$l[] = array(
			'id' => $product->id(),
			'code' => $product->code(),
			'name' => $product->name(),
			'model' => $product->model(),
			'fullName' => $product->fullName(),
			'image' => $product->image(),
			'manufacturerName' => $product->manufacturerName(),
			'manufacturerId' => $product->manufacturerId(),
			'price' => $product->price(),
			'rating' => $product->rating()
		);
	}
	return $l;
}


function getProduct($id)
{
	if (!$id) {
		return array();
	}
	
	$product = new \cf\Product($id);
	
	$groups = new \cf\ProductGroups($id,true);
	$attributes = $product->attributes();
	$aValues = array();
	foreach ($attributes as $a) {
		$aValues[$a->id()] = array(
			'name' => $a->name(),
			'value' => $a->value()
		);
	}
	return array(
		'id' => $product->id(),
		'code' => $product->code(),
		'name' => $product->name(),
		'fullName' => $product->fullName(),
		'price' => $product->price(),
		'groups' => $groups->IDs(),
		'attributes' => $aValues,
		'manufacturerName' => $product->manufacturerName(),
		'manufacturerId' => $product->manufacturerId(),
		'image' => $product->image(),
		'rating' => $product->rating(),
		'images' => $product->images(),
		'imageTexts' => $product->imageTexts(),
		'shortDescr' => $product->shortDescr(),
		'fullDescr' => $product->fullDescr()
	);
}

function addReview($productId, $rating, $review='')
{
	$userId = null;
	$user = \cf\User::getLoggedIn();
	if ($user) {
		$userId = $user->id();
	}
	
	return \cf\api\admin\doAction(
		'review_add',
		array('product_id'=>$productId, 'rating'=>$rating, 'review'=>$review, 'user_id'=>$userId)
	);
}

?>